<script src="https://cdn.amplitude.com/libs/analytics-browser-1.9.1-min.js.gz"></script>
<script type="text/javascript">
const amplitudeKey = "{{ config.extra.analytics.amplitude_key }}"
const amplitudeUrl = "{{ config.extra.analytics.amplitude_url }}"

const addUrl = (event) => {
  const deviceId = amplitude.getDeviceId()
  const { href = '' } = event.target
  const url = new URL(href)
  url.searchParams.set('deviceId', deviceId)
  event.target.href = url.toString()
}

const removeUrl = (event) => {
  const { href = '' } = event.target
  const url = new URL(href)
  url.searchParams.delete('deviceId')
  event.target.href = url.toString()
}

const urls = [
  'https://app.prefect.cloud',
  'https://app.stg.prefect.dev',
  'https://app.prefect.dev',
]

const selector = urls.map((url) => `a[href^="${url}"]`).join(',')

const addDeviceIdToAppLinks = () => {
  const elements = document.querySelectorAll(selector)

  elements.forEach((element) => {
    element.addEventListener('mouseenter', addUrl)
    element.addEventListener('mouseleave', removeUrl)
    element.addEventListener('focus', addUrl)
    element.addEventListener('blur', removeUrl)
    element.addEventListener('touchstart', addUrl)
    element.addEventListener('touchend', removeUrl)
  })
}


const init = () => {
  amplitude.init(amplitudeKey, undefined, {
    useBatch: true,
    serverUrl: amplitudeUrl,
    attribution: {
      disabled: false,
      trackNewCampaigns: true,
      trackPageViews: true,
      resetSessionOnNewCampaign: true,
    },
    defaultTracking: {
      pageViews: {
        trackOn: function() { return true},
        eventType: "Page View: Docs",
        trackHistoryChanges: "all",
      },
      sessions: false,
      formInteractions: true,
      fileDownloads: true,
    },
  })
}

function trackPageView() {
  amplitude.track(
    'Page View: Docs',
    {
      'url': window.href,
      'title': document.title,
      'referrer': document.referrer,
      'path': window.location.pathname
    }
  )
}

if (amplitudeKey){
  document.addEventListener("DOMContentLoaded", function() {
      init()
      setTimeout(addDeviceIdToAppLinks)
      setTimeout(trackPageView)
  });
}
</script>

{% include "partials/integrations/analytics/google.html" %}
